package com.zhengqian.boyunvcodemother.aop;

import com.zhengqian.boyunvcodemother.annotation.AuthCheck;
import com.zhengqian.boyunvcodemother.exception.BusinessException;
import com.zhengqian.boyunvcodemother.exception.ErrorCode;
import com.zhengqian.boyunvcodemother.model.entity.User;
import com.zhengqian.boyunvcodemother.model.enums.UserRoleEnum;
import com.zhengqian.boyunvcodemother.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 权限校验切面
 * 编写权限校验 AOP，采用环绕通知，在 打上该注解的方法 执行前后进行一些额外的操作，比如校验权限
 */
@Aspect
@Component
public class AuthInterceptor {
    @Resource
    private UserService userService;

    /**
     * 执行拦截
     * @param joinPoint 切入点
     * @param authCheck 权限校验注解
     * @return  a
     * @throws Throwable
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable{
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        //当前登录yoghurt
        User loginUser = userService.getLoginUser(request);
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        //不需要权限,放行
        if(mustRoleEnum==null){
            return joinPoint.proceed();
        }
        //必须有该权限才通过
        //获取当前用户具有的权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        //没有权限,拒绝
        if(userRoleEnum==null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //要求必须要有管理员的权限,但是用户没有管理员的权限,拒绝
        if(UserRoleEnum.ADMIN.equals(mustRoleEnum)
        &&!UserRoleEnum.ADMIN.equals(userRoleEnum)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //通过权限校验
        return joinPoint.proceed();

    }
}
